package com.zpyr.aop.annot;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.catalina.connector.RequestFacade;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import com.zpyr.common.CookieManager;
import com.zpyr.common.LogManager;
import com.zpyr.common.SessionManager;
import com.zpyr.common.StringUtil;

@Aspect
public class StartEndAspect {
	private LogManager logman;
	private long startTime , endTime;
	public StartEndAspect() {
		logman = new LogManager();
	}
	
	@Before("execution(public * com.zpyr.mvc..*.*(..) )")
	public String beforeAspect(JoinPoint joinPoint ) {
		String methodName = joinPoint.getSignature().getName();
		startTime = System.currentTimeMillis();
		
		HttpServletRequest req = null;
		
		for( Object obj : joinPoint.getArgs() ) {
			if(obj != null) {
				
				if( obj.getClass().getName().equals( RequestFacade.class.getName() ) ) {
					req = (HttpServletRequest)obj;
				}
			}
		}
		if(req == null) {
			return methodName;
		}
		
		SessionManager sess = SessionManager.getInstance( req );
		
		Cookie[] ckes = req.getCookies();
		
		String cke_login_id =  "";
		String cke_login_ip = "";
		if( ckes != null ) {
			for( Cookie cke : ckes ) {
				if( CookieManager.COOKIE_STR_LOGIN_EMAIL.equals( cke.getName() ) ) {
					cke_login_id = cke.getValue();
				}
				if( CookieManager.COOKIE_STR_LOGIN_IP.equals( cke.getName() ) ) {
					cke_login_ip = cke.getValue();
				}
			}
		}
		if(cke_login_ip != null && !cke_login_ip.equals("") && cke_login_ip.equals( StringUtil.encodeMD5(req.getRemoteHost()) ) ) {
			// ip 체크를 통과 했다면, id 값에 대한 인증도 필요하다만..
			if(cke_login_id.equals( StringUtil.encodeMD5("ocpek@nate.com")) ) {
				sess.setLoginEmail( "ocpek@nate.com" );
			}
		}
		
		/**
		 * AOP args 중에서 쿠키값을 찾아서 ip 값이 현재 ip 값과 똑같다면
		 */
		
		return methodName;
		
	}

	@AfterThrowing("execution(* com.zpyr.mvc..*.*(..) )")
	public String afterThrowAspect(JoinPoint joinPoint ) {
		
		String methodName = joinPoint.getSignature().getName();
	//	logman.debug("@AfterThrowing : " + methodName);
		return methodName;
		
	}
	@After("execution(* com.zpyr.mvc..*.*(..) )")
	public String afterAspect(JoinPoint joinPoint ) {
		endTime = System.currentTimeMillis();
		String methodName = joinPoint.getSignature().getName();
		logman.debug("@"+methodName + " 실행시간 : " + (endTime - startTime) + "밀리 초");
		return methodName;
		
	}
}
